﻿using AutoMapper;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using MySqlX.XDevAPI.Common;
using Org.BouncyCastle.Asn1.Ocsp;
using socialnetworkApp.Core;
using socialnetworkApp.Core.GlobalVariableClass;
using socialnetworkApp.Domain;
using socialnetworkApp.Domain.Dto.Input;
using socialnetworkApp.Domain.Dto.Output;
using socialnetworkApp.Domain.Manager;
using socialnetworkApp.Domain.Models;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using System.Xml.Linq;
using static System.Reflection.Metadata.BlobBuilder;
using Role = socialnetworkApp.Domain.Models.Role;

namespace socialnetworkApp.Service.AdminService
{
    public class AdminService : IAdminService
    {
        private readonly AdminManager _adminManager;
        private readonly UsersManager _usersManager;
        private readonly IMapper _mapper;
        public AdminService(AdminManager adminManager, IMapper mapper, UsersManager usersManager)
        {
            _adminManager = adminManager;
            _mapper = mapper;
            _usersManager = usersManager;
        }
        public async Task<ResponseResult<UsersListOutput>> GetUserListInfo(GetUserListInput input)
        {
            
            UsersListOutput usersListOutput = new UsersListOutput();
            List<Users> result;
            if (input.Id.IsNullOrEmpty())
            {
                usersListOutput = new UsersListOutput();
                return  ResponseResult<UsersListOutput>.Result(0, usersListOutput, "id不能为空");
            }
            Users users = new Users {Id=input.Id,Username=input.UserName };
            if (!string.IsNullOrEmpty(users.Username))
            {
                result = await _adminManager.GetUserListSearch(users);
            }
            else
            {
                result = await _adminManager.GetUserList(users);
            }
        
            var list = _mapper.Map<List<Record>>(result);
            var pageslist = list.Skip((input.PageNo - 1) * input.PageSize).Take(input.PageSize).ToList();
            long count = list.LongCount();
            //Math.Ceiling：向上进位取整。
            //总页码
            int pageCount = (int)Math.Ceiling(count * 1.0 / input.PageSize);
            usersListOutput.Size = input.PageSize;
            usersListOutput.Total = (int)count;
            usersListOutput.Pages =(int)count;
            usersListOutput.Records=pageslist;


            return  ResponseResult<UsersListOutput>.SuccessResult(usersListOutput);

        }


        public async Task<ResponseResult<toAssignRoleListOutput>> toAssign(string userid)
        {
            try
            {
                // 拿去全部的角色信息
                List<RoleDto> allRolesList = null;
                var role = new Role();
                var roles = await _adminManager.GetRoleList(role);
                allRolesList = _mapper.Map<List<RoleDto>>(roles);

                // 获取当前用户的角色数据
                List<RoleDto> assignRolesList = null;
                var users = new Users { Id = userid };
                var userinfo = await _adminManager.GetUserRole(users);

                // 如果用户角色信息为空，则返回全部角色列表和空的分配角色列表
                if (string.IsNullOrEmpty(userinfo.Roles))
                {
                    return ResponseResult<toAssignRoleListOutput>.SuccessResult(new toAssignRoleListOutput
                    {
                        allRolesList = allRolesList,
                        assignRoles = new List<RoleDto>()
                    });
                }

                //var Rids = userinfo.Roles.Split(',').ToList();
            
                List<string> Rids =JsonSerializer.Deserialize<List<string>>(userinfo.Roles);

                var rolesForUser = await _adminManager.GetRoleInfoById(Rids);
                assignRolesList = _mapper.Map<List<RoleDto>>(rolesForUser);

                // 准备返回结果
                var output = new toAssignRoleListOutput
                {
                    allRolesList = allRolesList,
                    assignRoles = assignRolesList
                };

                return ResponseResult<toAssignRoleListOutput>.SuccessResult(output);
            }
            catch (Exception ex)
            {
                // 记录异常日志（可以根据实际情况进行记录）
                // _logger.LogError(ex, "An error occurred while assigning roles.");

                // 返回失败结果
                return ResponseResult<toAssignRoleListOutput>.FailResult("发生错误，请稍后再试。");
            }
        }

        public async Task<ResponseResult<string>> UserAssignRoleAsync(AssignRoleInput assignRoleInput)
        {
            // 检查输入参数是否为空
            if (assignRoleInput == null || assignRoleInput.RoleIdList == null || !assignRoleInput.RoleIdList.Any() || string.IsNullOrWhiteSpace(assignRoleInput.UserId))
            {
                return ResponseResult<string>.FailResult("无效的输入参数");
            }

            try
            {
                // 将角色ID列表序列化为JSON字符串
                string roleListJson = JsonSerializer.Serialize(assignRoleInput.RoleIdList);

                // 创建一个Users对象，设置用户ID和角色列表
                Users user = new Users
                {
                    Id = assignRoleInput.UserId,
                    Roles = roleListJson
                };

                // 使用AdminManager更新用户角色
                long result = await _adminManager.UpdateUserRole(user);

                // 检查更新操作的结果
                if (result > 0)
                {
                    // 如果更新成功，返回成功结果
                    return ResponseResult<string>.SuccessResult();
                }

                // 如果更新不成功，返回失败结果
                return ResponseResult<string>.FailResult("系统异常");
            }
            catch (Exception ex)
            {
                // 记录异常（根据需要实现日志记录）
                // LogException(ex);

                // 返回带有异常消息的失败结果
                return ResponseResult<string>.FailResult($"系统异常: {ex.Message}");
            }
        }


        public async Task<ResponseResult<RoleListOutput>> GetRoleListInfo(GetRoleListInput input)
        {

            RoleListOutput RoleListOutput = new RoleListOutput();
            List<Role> result;
            if (input.Id.IsNullOrEmpty())
            {
                RoleListOutput = new RoleListOutput();
                return ResponseResult<RoleListOutput>.Result(0, RoleListOutput, "id不能为空");
            }
            Role role = new Role { Id = input.Id, RoleName = input.RoleName };
            if (!string.IsNullOrEmpty(role.RoleName))
            {
                result = await _adminManager.GetRoleListSearch(role);
            }
            else
            {
                result = await _adminManager.GetRoleList(role);
            }

            var list = _mapper.Map<List<RoleDto>>(result);
            var pageslist = list.Skip((input.PageNo - 1) * input.PageSize).Take(input.PageSize).ToList();
            long count = list.LongCount();
            //Math.Ceiling：向上进位取整。
            //总页码
            int pageCount = (int)Math.Ceiling(count * 1.0 / input.PageSize);
            RoleListOutput.Size = input.PageSize;
            RoleListOutput.Total = (int)count;
            RoleListOutput.Pages = (int)count;
            RoleListOutput.Records = pageslist;


            return ResponseResult<RoleListOutput>.SuccessResult(RoleListOutput);

        }


        public async Task<ResponseResult<string>> DeleteUser(string userid)
        {
            // 检查 userid 是否为空或 null
            if (string.IsNullOrWhiteSpace(userid))
            {
                return ResponseResult<string>.FailResult("用户ID不能为空！");
            }

            // 尝试将 userid 转换为 Guid
            if (!Guid.TryParse(userid, out Guid Id))
            {
                return ResponseResult<string>.FailResult("无效的用户ID！");
            }

            // 调用删除用户方法
            long res = await _adminManager.DeleteUser(Id);

            // 根据删除结果返回相应的响应
            if (res > 0)
            {
                return ResponseResult<string>.SuccessResult();
            }

            return ResponseResult<string>.FailResult("系统异常！");
        }

        public async Task<ResponseResult<string>> EditUser(InputUserDto inputUser)
        {
            Users users = new Users {Id=inputUser.Id,Username=inputUser.Username,
            Nickname=inputUser.Name, Phone=inputUser.Phone  ,Password=inputUser.Password, UpdateTime=DateTime.Now};
            if (string.IsNullOrWhiteSpace(users.Id))
             {
                return ResponseResult<string>.FailResult("用户ID不能为空！");
            }
            if (string.IsNullOrWhiteSpace(users.Username))
            {
                return ResponseResult<string>.FailResult("用户名不能为空！");
            }

             long res=  await   _adminManager.EditUser(users);
       

            // 根据删除结果返回相应的响应
            if (res > 0)
            {
                return ResponseResult<string>.SuccessResult();
            }

            return ResponseResult<string>.FailResult("系统异常！");
        }



        public async Task<ResponseResult<string>> AddRoleInfo(AddRoleInfoInput input)
        {
            // 验证RoleName是否非空  
            if (string.IsNullOrEmpty(input.RoleName))
            {
                return ResponseResult<string>.Result(ResultStatus.UnprocessableParam, null, "RoleName不能为空");
            }

            // 创建Role对象  
            Role role = new Role { RoleName = input.RoleName ,Remark=input.Remark };

            try
            {
                // 调用异步方法添加角色  
                int result = await _adminManager.AddRoleAsync(role);

                // 根据结果返回不同的ResponseResult  
                if (result > 0)
                {
                    return ResponseResult<string>.SuccessResult();
                }
                else
                {
                    // 如果result不是大于0，则可能表示添加失败，但最好使用明确的错误消息  
                    return ResponseResult<string>.Result(ResultStatus.Error, null, "添加角色失败");
                }
            }
            catch (Exception ex)
            {
                // 捕获并处理异常  
                // 这里可以根据需要记录日志或执行其他操作  
                return ResponseResult<string>.ErrorResult(ex.Message); // 假设ErrorResult有一个重载可以接受错误消息  
            }
        }

        /// <summary>
        /// 数据处理，将菜单数据处理为树状形式数据
        /// </summary>
        /// <param name="treeNodes">原始从数据库中取到</param>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<GetPermissionInfoOutput> BulidTreeByRecursive(List<GetPermissionInfoOutput> treeNodes, string id)
        {

            var tree = treeNodes.Where(x => x.Pid == id).ToList();

            for (int i = 0; i < tree.Count; i++)
            {
                tree[i].Children = BulidTreeByRecursive(treeNodes, tree[i].Id);
            }
            return tree;


        }

        /// <summary>
        /// 获取权限状态
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseResult<List<GetPermissionInfoOutput>>> GetPermissionInfo()
        {

              var result =  await  _adminManager.GetPermissionAsyncLisst();
           var list=   _mapper.Map<List<GetPermissionInfoOutput>>(result);
            // var json = JsonSerializer.Serialize(list);
            //JsonSerializer.Deserialize<List<GetPermissionInfoOutput>>(json);
            //将全部权限信息存储奥redis中
            var res = await RedisHelper.SetAsync("PermissionAsyncLisst", list);
            if(res){
                Console.WriteLine("Redis存储数据成功！");
            }
            var responseData=  BulidTreeByRecursive(list,"0");

            return ResponseResult<List<GetPermissionInfoOutput>>.SuccessResult(responseData);
        }

       /// <summary>
       /// 新增权限信息
       /// </summary>
       /// <param name="addPermission"></param>
       /// <returns></returns>
       /// <exception cref="NotImplementedException"></exception>
        public async Task<ResponseResult<string>> AddPermissionInfo(AddPermissionDto addPermission)
        {

            //var permission=   _mapper.Map<Permission>(addPermission);
            try
            {
                // 手动将 DTO 属性赋值给实体类
                var permission = new Permission
                {
                    Pid = addPermission.Pid,
                    Id = addPermission.Id.ToString(),
                    Name = addPermission.Name,
                    Code = addPermission.Code,
                    Level = addPermission.Level
                };

                // 检查字符串属性是否非空且非空字符串  
                if (string.IsNullOrEmpty(permission.Code) || string.IsNullOrEmpty(permission.Name) || string.IsNullOrEmpty(permission.Pid))
                {
                    return ResponseResult<string>.FailResult("字段不能空！");
                }

                // 获取 PermissionId 列表，确保 _adminManager 返回有效数据
                var permissionIdList = await _adminManager.SelectPermissionId();
                if (permissionIdList == null || !permissionIdList.Any())
                {
                    return ResponseResult<string>.FailResult("无法获取权限ID列表！");
                }

                // 使用 LINQ 提取 Id 并转换为 List<int>，同时处理无效转换
                List<int> intIdList = permissionIdList
                    .Select(p => p.Id)
                    .Where(id => int.TryParse(id.ToString(), out _)) // 过滤掉不能转换为 int 的 Id
                    .Select(id => Convert.ToInt32(id))               // 将有效的 Id 转换为 int
                    .ToList();

                if (!intIdList.Any())
                {
                    return ResponseResult<string>.FailResult("没有有效的权限ID可用！");
                }

                // 生成新 Id
                var newId = GenerateId(Convert.ToInt32(permission.Pid), intIdList);
                permission.Id = newId.ToString();

                // 保存 Permission，确保保存操作成功
                long res = await _adminManager.SavePermission(permission);
                if (res > 0)
                {
                    return ResponseResult<string>.SuccessResult();
                }
                else
                {
                    return ResponseResult<string>.FailResult("保存权限时出现错误！");
                }
            }
            catch (FormatException ex)
            {
                // 处理转换异常，例如字符串无法转换为整数
                return ResponseResult<string>.FailResult($"ID 转换失败: {ex.Message}");
            }
            catch (ArgumentNullException ex)
            {
                // 处理空引用异常
                return ResponseResult<string>.FailResult($"空值错误: {ex.Message}");
            }
            catch (Exception ex)
            {
                // 捕获所有其他类型的异常
                return ResponseResult<string>.FailResult($"发生未知错误: {ex.Message}");
            }
        }
        /// <summary>
        /// 偏移查找
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="num"></param>
        /// <returns></returns>
        public static int GenerateId(int pid, List<int> num)
        {
            int offset = 1;  // 用于偏移查找 从1开始跳过自己
            while (true)
            {
                int potentialId = 0;

                // 尝试生成比pid小的数
                // potentialId = pid - offset;
                //if (!num.Contains(potentialId) && potentialId > 0) // 确保生成的id不在num中，并且为正数
                //{
                //    return potentialId;
                //}

                // 尝试生成比pid大的数
                potentialId = pid + offset;
                if (!num.Contains(potentialId)) // 使用 List 的 Contains 方法
                {
                    return potentialId;
                }

                offset++; // 增加偏移量，继续查找
            }
        }

        public async Task<ResponseResult<List<GetPermissionInfoOutput>>> GetPermissionInfoById(string RoleId) {
            List<GetPermissionInfoOutput> infoOutputs = new List<GetPermissionInfoOutput>();
            var result = await _adminManager.GetPermissionAsyncLisst();
            var list = _mapper.Map<List<GetPermissionInfoOutput>>(result);
             List<string> roleIds = new List<string>();
            roleIds.Add(RoleId);
          var  RouteAndButtonIds =await _adminManager.ExtractRouteAndButtonIdsFromRolePermissionsAsync(list, roleIds);
            List<List<string>> lists = new List<List<string>> { RouteAndButtonIds.RouteIds, RouteAndButtonIds.ButtonIds };
              //var Ids= _adminManager.MergeAndRemoveDuplicates(lists);
            List<string> permissionInfoIds = lists.SelectMany(list => list).ToList();

            infoOutputs =  SetSelectField(list, permissionInfoIds);
            var responseData = BulidTreeByRecursive(infoOutputs, "0");
            return ResponseResult<List<GetPermissionInfoOutput>>.SuccessResult(responseData);
        }

        /// <summary>
        /// 判断有相应的权限就设置select为true
        /// </summary>
        /// <param name="permissionInfos"></param>
        /// <param name="ids"></param>
        public static List<GetPermissionInfoOutput> SetSelectField(List<GetPermissionInfoOutput> permissionInfos, List<string> ids)
        {
            foreach (var permissionInfo in permissionInfos)
            {
                if (ids.Contains(permissionInfo.Id))
                {
                    permissionInfo.Select = true;
                    
                }
            }

            return permissionInfos;
        }

        public async Task<ResponseResult<string>> AssignPermissionsToRole(string roleId, List<string> permissionIds)
         {
            var buttonIds = new List<string>();
            var routeIds = new List<string>();

            var permissionsJson = await RedisHelper.GetAsync("PermissionAsyncLisst");
            var permissions = JsonSerializer.Deserialize<List<GetPermissionInfoOutput>>(permissionsJson);

            foreach (var permission in permissions)
            {
                if (permission.Code != null)
                {
                    if (permissionIds.Contains(permission.Id))
                    {//判断如果是btn权限另外放一个list中存储
                        if (permission.Code.Contains("btn"))
                        {
                            buttonIds.Add(permission.Id);
                        }
                        else
                        {
                            routeIds.Add(permission.Id);
                        }
                    }

                }
                else if (permission.Code != null || permission.Id=="1")
                {
                    routeIds.Add(permission.Id);
                }
            }

            var role = new Role { Id = roleId, Routes = JsonSerializer.Serialize(routeIds), Buttons = JsonSerializer.Serialize(buttonIds) };
            var result = await _adminManager.UpdateRoleAsync(role);

            return result > 0 ? ResponseResult<string>.SuccessResult() : ResponseResult<string>.FailResult("Update failed");
        }
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="addUserInput"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ResponseResult<string>> CreateUser(AddUserInput addUserInput)
        {
            if (addUserInput == null)
            {
                return ResponseResult<string>.FailResult("参数为null！");
            }

            if (string.IsNullOrWhiteSpace(addUserInput.Username) || string.IsNullOrWhiteSpace(addUserInput.Password) || string.IsNullOrWhiteSpace(addUserInput.Name))
            {
                return ResponseResult<string>.FailResult("用户名、密码或名称不能为空！");
            }

            string uid = Guid.NewGuid().ToString();
            Users users = new Users
            {
                Id = uid,
                Username = addUserInput.Username,
                Password = addUserInput.Password,
                Nickname = addUserInput.Name
            };

            long res = await _usersManager.AddUser(users);

            return res > 0 ? ResponseResult<string>.SuccessResult() : ResponseResult<string>.FailResult();
        }

        /// <summary>
        /// 删除菜单id
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>

        public async Task<ResponseResult<string>> RemovePermissionInfo(string pid)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(pid))
                {
                    return ResponseResult<string>.ErrorResult("系统异常！");
                }
                long res = await _adminManager.RemovePermission(pid);

                if (res > 0)
                {

                    return ResponseResult<string>.SuccessResult("删除成功！");
                }
            }
            catch (Exception ex)
            {

                return ResponseResult<string>.FailResult(ex.Message);
            }


            return ResponseResult<string>.ErrorResult("系统异常！");

        }

    
    }
}
